
const request = require('sync-request');

const {User, PortalJobMeta, sequelize} = require('./database');

const driver_url = 'http://10.141.212.118:8082';

function generateRequest(sql, offset, limit, task_id){
    var reqData = {
        sql: sql,
        offset: offset,
        limit: limit,
        acceptPartial: false,
        project: task_id
    };
    return reqData;
}

function getColumns(table) {
    var FormData = request.FormData;
    var formData = new FormData();
    formData.append('table', table);
    var res = request('POST', driver_url+'/columns', {
        body: 'table='+table
    });
    // console.log(JSON.stringify(formData));
    // console.log('get columns for table[', table,'] and the result is: ', res.getBody('utf8'));
    var columns = JSON.parse(res.getBody('utf8'));
    return columns;
}

function getData(table, task_id) {
    var res = request('POST', driver_url+'/columns', {
        body: 'table='+table
    });
    var cols = JSON.parse(res.getBody('utf8'));
    console.log("getData columns: ", cols);
    // var cols = JSON.parse(columns);
    var sql = "select "+cols.join(',')+",COUNT(*) as _COUNT_ from "+table+" group by "+cols.join(',')+";";
    var offset = 0;
    var limit = 10000;
    var reqData = generateRequest(sql, offset, limit, task_id);

    var options = {
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Basic QURNSU46S1lMSU4="
        },
        json: reqData
    };
    var url = 'http://10.141.212.118:7070/kylin/api/query';
    console.log("request [", url,"] request data is: ", reqData);
    res = request('POST', url, options);
    // console.log(res.getBody('utf8'));

    var ret = JSON.parse(res.getBody('utf8'));
    return ret;
}

function getTables(){
    var ret = request('GET', driver_url+'/list');
    console.log('Tables: ', ret.getBody('utf8'));
    return JSON.parse(ret.getBody('utf8'));
}



module.exports = {
    getColumns:getColumns, getData:getData, getTables:getTables
};
